package com.cta.tcp.server;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;

import java.util.Map;

public class JsonUtils {

    private static ObjectMapper mapper = null;


    public static ObjectMapper getObjectMapper() {
        if (mapper == null) {
            mapper = new ObjectMapper();
        }
        return mapper;
    }


    public static String toString(Object o) {
        try {
            return getObjectMapper().writeValueAsString(o);
        } catch (Exception e) {
            return null;
        }
    }


    public static <T> T parseJsonType(String json, Class<T> valueType) {
        try {
            getObjectMapper().configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            return getObjectMapper().readValue(json, valueType);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T map2Obj(Map map, Class<T> valueType) {
        try {
            return getObjectMapper().convertValue(map, valueType);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
